package com.example.xmpic.ui.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.collection.LruCache;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.common.utils.LiveDataBus;
import com.example.xmpic.R;
import com.example.xmpic.R2;
import com.example.xmpic.support.FunPath;
import com.example.xmpic.support.FunSupport;
import com.example.xmpic.support.OnFunDeviceFileListener;
import com.example.xmpic.support.models.FunDevice;
import com.example.xmpic.support.models.FunFileData;
import com.example.xmpic.support.utils.Define;
import com.lib.EUIMSG;
import com.lib.FunSDK;
import com.lib.IFunSDKResult;
import com.lib.MsgContent;
import com.lib.sdk.struct.H264_DVR_FILE_DATA;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author skygge
 * @date 2020/6/9.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class RecordListAdapter extends RecyclerView.Adapter<RecordListAdapter.ItemHolder> implements OnFunDeviceFileListener, IFunSDKResult {

    private Context mContext;
    private List<FunFileData> mFiles;
    private List<FunFileData> mDownloadFiles;
    private int mPosition = -1;
    private boolean mShowSelect = false;

    private int mUserId;
    private FunDevice mFunDevice;
    private LruCache<String, Bitmap> mLruCache;
    private RecyclerView mImageList;

    private enum CheckType {CHECKED, UNCHECK}
    private List<CheckType> mCheckList;

    public RecordListAdapter(Context mContext, FunDevice funDevice) {
        this.mContext = mContext;
        this.mFunDevice = funDevice;
        mDownloadFiles = new ArrayList<>();
        mCheckList = new ArrayList<>();
        initLruCache();
        mUserId = FunSDK.GetId(mUserId,this);
    }

    private void initLruCache() {
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        // 设置图片缓存大小为maxMemory的1/3
        int cacheSize = maxMemory / 3;
        mLruCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(@NonNull String key, @NonNull Bitmap bitmap) {
                return bitmap.getRowBytes() * bitmap.getHeight();
            }
        };
    }

    public void setFiles(List<FunFileData> mFiles, RecyclerView recyclerView) {
        this.mFiles = mFiles;
        this.mImageList = recyclerView;
        initCheckData(false);
    }

    public void setPosition(int mPosition) {
        this.mPosition = mPosition;
        notifyDataSetChanged();
    }

    public List<FunFileData> getDownloadFiles() {
        return mDownloadFiles;
    }

    public void selectAllFiles(){
        initCheckData(true);
        notifyDataSetChanged();
    }

    public void cancelDownload(){
        mShowSelect = false;
        mDownloadFiles.clear();
        initCheckData(false);
        notifyDataSetChanged();
    }

    private void initCheckData(boolean isCheck) {
        int size = mFiles.size();
        mCheckList.clear();
        for (int i = 0; i < size; i++) {
            CheckType checkType = isCheck ? CheckType.CHECKED : CheckType.UNCHECK;
            mCheckList.add(checkType);
        }
    }

    @NonNull
    @Override
    public ItemHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_record_list, viewGroup, false);
        return new ItemHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ItemHolder itemHolder, int i) {
        FunFileData funFileData = mFiles.get(i);
        itemHolder.recordTime.setText(funFileData.getBeginTimeStr());
        if (mShowSelect){
            itemHolder.recordPlay.setVisibility(View.GONE);
            itemHolder.recordSelect.setVisibility(View.VISIBLE);
        }else {
            itemHolder.recordSelect.setVisibility(View.GONE);
            itemHolder.recordPlay.setVisibility(View.VISIBLE);
            itemHolder.recordPlay.setImageResource(mPosition == i ? R.mipmap.icon_record_play : R.mipmap.icon_record_stop);
        }

        setImageForImageView(i, funFileData.getCapTempPath(), itemHolder.recordImage);

        itemHolder.recordSelect.setOnCheckedChangeListener((buttonView, isChecked) -> {
            mCheckList.set(i, isChecked ? CheckType.CHECKED : CheckType.UNCHECK);
            if (mCheckList.get(i) == CheckType.CHECKED){
                mDownloadFiles.add(funFileData);
            }else if (mCheckList.get(i) == CheckType.UNCHECK){
                mDownloadFiles.remove(funFileData);
            }
        });

        itemHolder.recordSelect.setChecked(mCheckList.get(i) == CheckType.CHECKED);

        itemHolder.recordPlay.setOnClickListener(v ->
                LiveDataBus.get().with("RECORD_PLAY").setValue(funFileData));

        itemHolder.itemView.setOnLongClickListener(v -> {
            LiveDataBus.get().with("RECORD_DOWNLOAD").setValue(1);
            mShowSelect = true;
            notifyDataSetChanged();
            return false;
        });
    }

    @Override
    public int getItemCount() {
        return mFiles == null ? 0 : mFiles.size();
    }

    @Override
    public void onDeviceFileDownCompleted(FunDevice funDevice, String path, int nSeq) {
        mHandler.obtainMessage(0, nSeq).sendToTarget();
    }

    @Override
    public void onDeviceFileDownProgress(int totalSize, int progress, int nSeq) {

    }

    @Override
    public void onDeviceFileDownStart(boolean isStartSuccess, int nSeq) {

    }

    @Override
    public int OnFunSDKResult(Message msg, MsgContent ex) {
        switch (msg.what) {
            case EUIMSG.DOWN_RECODE_BPIC_START: //录像缩略图下载开始
                break;
            case EUIMSG.MC_DownloadMediaThumbnail:
            case EUIMSG.DOWN_RECODE_BPIC_FILE: //录像缩略图下载--文件下载结果返回
                if (ex.seq < mFiles.size()) {
                    FunFileData funFileData =  mFiles.get(ex.seq);
                    if (funFileData != null) {
                        H264_DVR_FILE_DATA info = funFileData.getFileData();
                        info.downloadStatus = Define.ON_DOWNLOAD_COMPLETE;
                        funFileData.setCapTempPath(ex.str);
                        setItemBitmap(ex.seq);
                    }
                }
                break;
            case EUIMSG.DOWN_RECODE_BPIC_COMPLETE://录像缩略图下载-下载完成（结束）

                break;
        }
        return 0;
    }

    private Handler mHandler = new Handler(msg -> {
        setItemBitmap((int)msg.obj);
        return false;
    });

    /**
     * 为ImageView设置图片(Image) 1 从缓存中获取图片 2 若图片不在缓存中则为其设置默认图片
     */
    private void setImageForImageView(int position, String imagePath, ImageView imageView) {
        imageView.setTag("image:" + position);
        Bitmap bitmap;
        if ( null != imagePath && imagePath.length() > 0 ) {
            bitmap = getBitmapFromLruCache(imagePath);
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
                return;
            }
        }

        bitmap = loadBitmap(position,true);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        }else {
            imageView.setImageResource(R.color.thumbnail_bg_color);
        }
    }

    private Bitmap loadBitmap(int position, boolean toDownload) {
        if ( position >= 0 && position < mFiles.size() ) {
            FunFileData funFileData = mFiles.get(position);
            H264_DVR_FILE_DATA info = funFileData.getFileData();
            if (null == info || info.st_3_beginTime.st_0_year == 0) {
                return null;
            }

            String fileName = FunPath.PATH_PHOTO_TEMP + File.separator + FunPath.getDownloadFileNameByData(info, 1, true);
            final long fileSize_thumb = FunPath.isFileExists(fileName);
            if (fileSize_thumb > 0) {
                Bitmap bitmap = getBitmapFromLruCache(fileName);
                if (null == bitmap) {
                    bitmap = dealBitmap(fileName);
                }

                if (null != bitmap) {
                    addBitmapToLruCache(fileName, bitmap);
                    return bitmap;
                } else {
                    FunPath.deleteFile(fileName);
                }
            }else if (toDownload) {
                int time = FunSDK.ToTimeType(new int[]{info.st_3_beginTime.st_0_year,
                        info.st_3_beginTime.st_1_month, info.st_3_beginTime.st_2_day,
                        info.st_3_beginTime.st_4_hour, info.st_3_beginTime.st_5_minute,
                        info.st_3_beginTime.st_6_second});
                FunSDK.DownloadRecordBImage(mUserId, mFunDevice.getDevSn(), 0, time, fileName, 0, position);
            }
        }
        return null;
    }

    private Bitmap dealBitmap(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false; // 设置了此属性一定要记得将值设置为false
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        if (bitmap == null)
            return null;
        Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, 160, 90, true);
        bitmap.recycle();
        return newBitmap;
    }

    private void setItemBitmap(int position) {
        FunFileData fileData = mFiles.get(position);
        if ( null == fileData ) {
            return;
        }
        ImageView iv = mImageList.findViewWithTag("image:" + position);
        if ( null != iv ) {
            Bitmap bmp = loadBitmap(position, false);
            if ( null != bmp ) {
                iv.setImageBitmap(bmp);
            }
        }
    }

    /**
     * 将图片存储到LruCache
     */
    private void addBitmapToLruCache(String key, Bitmap bitmap) {
        if (mLruCache != null) {
            synchronized (mLruCache) {
                if (getBitmapFromLruCache(key) == null && bitmap != null) {
                    mLruCache.put(key, bitmap);
                }
            }
        }
    }

    /**
     * 从LruCache缓存获取图片
     */
    private Bitmap getBitmapFromLruCache(String key) {
        if ( null == mLruCache ) {
            return null;
        }

        return mLruCache.get(key);
    }

    public void release() {
        FunSupport.getInstance().removeOnFunDeviceFileListener(this);

        if ( null != mHandler ) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }

        if ( null != mLruCache ) {
            mLruCache.evictAll();
            mLruCache = null;
        }
    }

    static class ItemHolder extends RecyclerView.ViewHolder {
        @BindView(R2.id.record_img)
        ImageView recordImage;
        @BindView(R2.id.record_time)
        TextView recordTime;
        @BindView(R2.id.record_play)
        ImageView recordPlay;
        @BindView(R2.id.record_select)
        CheckBox recordSelect;
        ItemHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
